package org.vacoor.xqq.reply.impl.result;

import com.fasterxml.jackson.databind.JsonNode;
import org.vacoor.xqq.core.bean.Buddy;
import org.vacoor.xqq.core.bean.Category;
import org.vacoor.xqq.reply.BuddiesResolver;
import org.vacoor.xqq.reply.impl.JsonResolver;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 */
public class SimpleBuddiesResolver extends JsonResolver<List<Category<Buddy>>> implements BuddiesResolver {

    @Override
    protected List<Category<Buddy>> doResolveResult(JsonNode result) {
        Map<Integer, Category<Buddy>> categories = new LinkedHashMap<Integer, Category<Buddy>>();
        Map<Long, Buddy> buddies = new LinkedHashMap<Long, Buddy>();

        for (JsonNode c : result.get("categories")) {
            int index = c.get("index").asInt();
            int sort = c.get("sort").asInt();
            String name = c.get("name").asText();
            Category category = createCategory(index, name);
            category.setSort(sort);
            categories.put(index, category);
        }

        for (JsonNode friend : result.get("friends")) {
            int cIdx = friend.get("categories").asInt();
            long uin = friend.get("uin").asLong();
            Category category = categories.get(cIdx);
            if (category == null) {
                if (cIdx != 0) {        // 应该只会缺少默认分组...
                    continue;
                }
                categories.put(cIdx, category = createCategory(cIdx, "我的好友"));
            }
            Buddy buddy = createBuddy(uin);
            buddies.put(uin, buddy);
            category.addPeer(buddy);
        }

        for (JsonNode info : result.get("info")) {
            long uin = info.get("uin").asLong();
            String nick = info.get("nick").asText();
            Buddy buddy = buddies.get(uin);
            if (buddy != null) {        // 不应该会出现 null
                buddy.setNick(nick);
            }
        }

        for (JsonNode markName : result.get("marknames")) {
            long uin = markName.get("uin").asLong();
            String mark = markName.get("markname").asText();
            Buddy buddy = buddies.get(uin);
            if (buddy != null) {        // 不应该会出现 null
                buddy.setMark(mark);
            }
        }

        // 排序后返回
//        List<Category> sorted = new LinkedList<Category>(categories.values());
//        Collections.sort(sorted, new Category.SortableComparator());
        return new LinkedList<Category<Buddy>>(categories.values());
    }

    protected Category<Buddy> createCategory(int index, String name) {
        return new Category<Buddy>(index, name);
    }

    protected Buddy createBuddy(long uin) {
        return new Buddy(uin);
    }
}
